package lambda_expression.jdk;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.function.ToIntFunction;
import java.util.stream.Collectors;

/**
 * Predicate<T>
 * 接收一个参数对象T，返回一个Boolean类型的结果
 */
public class PredicateTest {

    public static void main(String[] args) {

        Predicate<String> predicate = (String name) -> {
            return name.equals("admin");
        };

        System.out.println(predicate.test("admin"));

        System.out.println("============================================");

        List<String> list = new ArrayList<String>(){
            {
                add("zhangsan");
                add("lisi");
                add("wangwu");
                add("zhaoliu");
                add("qiqi");
            }
        };

        // zhangsan=wangwu=zhaoliu
        System.out.println(filterString(list, s -> s.length() > 5).stream().collect(Collectors.joining("=")));

        List<String> list2 = Arrays.asList("北京", "东京" ,"西安", "上海", "东京", "西京", "广州");
        // [北京, 东京, 东京, 西京]
        System.out.println(filterString(list2, s -> s.contains("京")).stream().collect(Collectors.toList()));
    }

    /**
     * 根据给定的规则，过滤集合中的字符串，此规则由Predicate的实现方法决定
     * @param list
     * @param predicate
     * @return
     */
    public static List<String> filterString(List<String> list, Predicate<String> predicate) {
        List<String> filterList = new ArrayList<>();
        list.forEach(s -> {
            if (predicate.test(s)) {
                filterList.add(s);
            }
        });
        return filterList;
    }
}
